//
//  PersonalInfoViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-30.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "NYMemberCenterDataManager.h"
#import "ChangeNameViewController.h"
#import "PhoneOriginalViewController.h"
#import "ModifyPwdViewController.h"
#import "GesturePwdViewController.h"
#import "ModifyAddressViewController.h"
#import "ChangePhoneViewController.h"
#import "UIImage+Utilities.h"
#import "UIImage-Extensions.h"
#import "JSON.h"
#import "PersonInfoCell.h"
#import "NYElement.h"
#import "MenuDataManager.h"
#import "NYLogoutManager.h"
#import "MemberChosenViewController.h"

@interface PersonalInfoViewController ()

@end

@implementation PersonalInfoViewController

@synthesize infoTableView,properties;

#pragma mark - Notification methods
- (void)changeNameSucceedWithNotification:(NSNotification *)notification
{
    [self.infoTableView reloadData];
}

- (void)iconChangedWithNotification:(NSNotification *)notification
{
    [self.infoTableView reloadData];
}

- (void)reloadPersonalInfoViewWithNotification:(NSNotification *)notification
{
    [self.infoTableView reloadData];
}
#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNameSucceedWithNotification:) name:kChangeNameSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iconChangedWithNotification:) name:kIconChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadPersonalInfoViewWithNotification:) name:kReloadPersonInfoViewNotification object:nil];
    [self setNaviTitle:@"个人信息"];
    
    self.properties = [NSMutableArray arrayWithObjects:@"头像",@"用户名",@"手机",@"登录密码",nil];
    
    
    NYElement *nye = nil;
    for(NYElement *element in [MenuDataManager sharedManager].elements)
    {
        if([element.elementId isEqualToString:kGesturePassCell])
        {
            nye = element;
            break;
        }
    }
    
    if(nye.elementAccess != kElementInvisiable)
    {
        [self.properties addObject:@"手势密码"];
    }
    if([NYMemberCenterDataManager sharedManager].memberRoles.count > 1)
    {
        [self.properties addObject:@"账户切换"];
    }
    
    CGRect rect = self.infoTableView.frame;
    rect.size.height = 70+55*(self.properties.count-1);
    self.infoTableView.frame = rect;
    self.infoTableView.scrollEnabled = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        self.view = nil;
        self.infoTableView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.infoTableView = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [infoTableView release];
    [properties release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.properties.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";

    PersonInfoCell *cell = nil;
    UIImage *acceImage = nil;
    UIImage *acceHighlightedImage = nil;

    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (nil == cell) {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"PersonInfoCell" owner:self options:nil];
        cell = [nibs lastObject];
        UIImageView *bgView = [[UIImageView alloc] initWithFrame:cell.bounds];
        bgView.image = [UIImage imageNamed:@"list_highlighted@2x"];
        cell.selectedBackgroundView = bgView;
        [bgView release];
    }
    
    switch (indexPath.row) {
        case 0:
            acceImage = [UIImage imageNamed:@"icon1_normal@2x"];
            acceHighlightedImage = [UIImage imageNamed:@"icon1_highlighted@2x"];
            break;
        case 1:
            acceImage = [UIImage imageNamed:@"icon8_normal@2x"];
            acceHighlightedImage = [UIImage imageNamed:@"icon8_highlighted@2x"];
            //cellText = [NSString stringWithFormat:@"自定义用户名"];
            break;
        case 2:
            acceImage = [UIImage imageNamed:@"icon7_normal@2x"];
            acceHighlightedImage = [UIImage imageNamed:@"icon7_highlighted@2x"];
            //cellText = [NSString stringWithFormat:@"寄送地址"];
            break;
        default:
            acceImage = [UIImage imageNamed:@"icon1_normal@2x"];
            acceHighlightedImage = [UIImage imageNamed:@"icon1_highlighted@2x"];
            break;
    }

    cell.accImageView.image = acceImage;
    cell.accImageView.highlightedImage = acceHighlightedImage;
    cell.titleLabe.text = [self.properties objectAtIndex:indexPath.row];
    [cell.titleLabe setHighlightedTextColor:[UIColor blackColor]];
    
    if (indexPath.row !=0) {
        cell.headImageView.hidden = YES;
        cell.headBgImageView.hidden = YES;
    }
    else{
        cell.headImageView.cacheDir = kUserImagesDir;
        [cell.headImageView aysnLoadImageWithUrl:[NYMemberCenterDataManager sharedManager].loginMember.userIcon placeHolder:@"loading_icon@2x"];
        cell.headImageView.hidden = NO;
        cell.headBgImageView.hidden = NO;
    }

    return cell;
}

#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.row == 0)
    {
        UIActionSheet *as = [[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从手机相册选择", nil] autorelease];
        [as showInView:self.view];
    }
    else if(indexPath.row == 1)
    {
        ChangeNameViewController *cnvc = [[ChangeNameViewController alloc] init];
        [self.navigationController pushViewController:cnvc animated:YES];
        [cnvc release];
    }
    else if(indexPath.row == 2)
    {
        if ([NYMemberCenterDataManager sharedManager].loginMember.memberType == kMemberRegister) {
            PhoneOriginalViewController *povc = [[PhoneOriginalViewController alloc] init];
            [self.navigationController pushViewController:povc animated:YES];
            [povc release];
        }
        
        else if([NYMemberCenterDataManager sharedManager].loginMember.memberType == kMemberAuthentication)
        {
            ChangePhoneViewController *cpvc = [[ChangePhoneViewController alloc] init];
            [self.navigationController pushViewController:cpvc animated:YES];
            [cpvc release];
        }

    }
    //else if(indexPath.row == 3)
    //{
        //ModifyAddressViewController *mavc =[[ModifyAddressViewController alloc]init];
        //[self.navigationController pushViewController:mavc animated:YES];
        //[mavc release];
    //}
    else if(indexPath.row == 3)
    {
        ModifyPwdViewController *mdvc = [[ModifyPwdViewController alloc] init];
        [self.navigationController pushViewController:mdvc animated:YES];
        [mdvc release];
    }
    else if(indexPath.row == 4)
    {
        GesturePwdViewController *gpvc = [[GesturePwdViewController alloc] init];
        [self.navigationController pushViewController:gpvc animated:YES];
        [gpvc release];
    }
    else if(indexPath.row == 5)
    {
        MemberChosenViewController *mcvc = [[MemberChosenViewController alloc] init];
        mcvc.isFromLogin = NO;
        [self.navigationController pushViewController:mcvc animated:YES];
        [mcvc release];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 70;
    }
    return 55;
}

#pragma mark - UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [RYMediaPicker sharedPicker].delegate = self;
    [RYMediaPicker sharedPicker].showExtraInfo = NO;
    [RYMediaPicker sharedPicker].parentController = self;
    [RYMediaPicker sharedPicker].mediaEditing = YES;
    [RYMediaPicker sharedPicker].fileType = kPhotoType;
    if(buttonIndex == 0)
    {
        //拍照
        [[RYMediaPicker sharedPicker] takePhotoWithCamera];
        
    }
    else if(buttonIndex == 1)
    {
        //手机相册选择
        [[RYMediaPicker sharedPicker] getPhotoFromLibrary];
    }
}

#pragma mark - RYMediaPickerDelegate methods
- (void)didGetFileWithData:(RYMediaPicker *)mediaPicker
{
    //编辑过的图片尺寸640*640，大小约350KB，压缩为120*120大小的图片，约20KB
    //本地保存当前选中的图片，同时上传至服务器
    UIImage *originalImage = [UIImage imageWithData:mediaPicker.fileData];
    CGSize userIconSize = [UIImage equalScaleSizeForMaxSize:kUserIconSize actualSize:originalImage.size];
    UIImage *userIconImage = [originalImage imageByScalingProportionallyToSize:userIconSize];
    
    NSString *userIconDir = [DOCUMENTS_FOLDER stringByAppendingPathComponent:kUserImagesDir];
    NSString *userIconPath = [NSString stringWithFormat:@"%@/%@",userIconDir,mediaPicker.fileName];
    NSFileManager *manager = [NSFileManager defaultManager];
    if(![manager fileExistsAtPath:userIconDir])
        [manager createDirectoryAtPath:userIconDir withIntermediateDirectories:NO attributes:nil error:nil];    
    NSData *userIconData = UIImageJPEGRepresentation(userIconImage, 1);
    [userIconData writeToFile:userIconPath atomically:NO];
    
    //上传服务器
    NSString *suburl = kChangeUserIconUrl;
    suburl = [suburl stringByAppendingString:@"app000008"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"jsonp" forKey:@"callback"];
    [dict setObject:[NYMemberCenterDataManager sharedManager].loginMember.accountId forKey:@"accountId"];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[RYDownloaderManager sharedManager] uploadFileByPostWithURLString:url
                                                            postParams:dict
                                                           contentType:@"multipart/form-data"
                                                              fileData:userIconData
                                                              fileType:@"image/jpg"
                                                              fileName:mediaPicker.fileName
                                                               fileKey:@"FILE1"
                                                              delegate:self
                                                               purpose:userIconPath];
}
- (void)didGetFileFailedWithMessage:(NSString *)mes
{
    [[RYHUDManager sharedManager] showWithMessage:mes customView:nil hideDelay:2.f];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        [NYMemberCenterDataManager sharedManager].loginMember.userIcon = downloader.purpose;
        [[NSNotificationCenter defaultCenter] postNotificationName:kIconChangedNotification object:nil];
    }
    else
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:downloader.purpose error:nil];
    }
    [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:downloader.purpose error:nil];
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - action methord
- (IBAction)logoutButtonPressed:(id)sender {
    UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"确认登出？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil] autorelease];
    [av show];
}

#pragma mark - UIAlertViewDelegate methods
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kAsynMenuNotification object:nil];
        [[NYLogoutManager sharedManager] callServerToLogout];
        [[NYMemberCenterDataManager sharedManager] logout];
        [[NSNotificationCenter defaultCenter] postNotificationName:kUserChangeNotification object:nil];
        //    [[NSNotificationCenter defaultCenter] postNotificationName:kLoadLeftMenuFirstTabNotification object:nil];
    }
}
@end
